package com.cqc.lite.web;


import com.cqc.lite.domain.Product;
import com.cqc.lite.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Role;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("/product/")
public class ProductController {


    private final ProductService productService;

    @Autowired
    public ProductController(ProductService productService){
        this.productService=productService;
    }


    @RolesAllowed({"ROLE_ADMIN"})
    @PostMapping("save.do")
    public String save(Product product){
        productService.save(product);
        return "redirect:/product/findAll.do";
    }

    @RolesAllowed({"ROLE_USER","ROLE_ADMIN"})
    @GetMapping("findAll.do")
    public ModelAndView findAll() throws Exception {
        List<Product> list = productService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("product-list");
        mv.addObject("productList",list);
        return mv;
    }
}
